import * as vscode from 'vscode';
import * as path from 'path';
import { LsykUploadPanel } from './panel';
import { LsykApi } from './api';

// 相册选项接口
interface AlbumOption {
    label: string;
    description: string;
    detail?: string;
    id: number | null;
}

export function activate(context: vscode.ExtensionContext) {
    console.log('lsyk-upload-vs-plugin is now active!');

    // 创建API实例
    const api = new LsykApi(context);

    // 注册上传图片命令
    const uploadImageDisposable = vscode.commands.registerCommand('lsyk-upload-vs-plugin.uploadImage', async () => {
        try {
            // 显示文件选择对话框
            const fileUri = await vscode.window.showOpenDialog({
                canSelectFiles: true,
                canSelectFolders: false,
                canSelectMany: false,
                filters: {
                    '图片文件': ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg']
                }
            });

            if (fileUri && fileUri.length > 0) {
                const filePath = fileUri[0].fsPath;

                // 获取相册列表
                let selectedAlbumId: number | undefined;
                const albumResult = await api.getAlbums();
                if (albumResult && albumResult.status && albumResult.data.data.length > 0) {
                    // 创建相册选择项
                    const albumItems: AlbumOption[] = albumResult.data.data.map(album => ({
                        label: album.name,
                        description: `${album.image_num}张图片`,
                        detail: album.intro || '无描述',
                        id: album.id
                    }));

                    // 添加"无相册"选项
                    albumItems.unshift({
                        label: '无相册',
                        description: '不指定相册',
                        id: null
                    });

                    // 显示选择面板
                    const selectedAlbum = await vscode.window.showQuickPick(albumItems, {
                        placeHolder: '请选择要上传到的相册',
                        canPickMany: false
                    });

                    if (selectedAlbum) {
                        selectedAlbumId = selectedAlbum.id ?? undefined;
                    }
                }

                // 上传图片
                vscode.window.withProgress({
                    location: vscode.ProgressLocation.Notification,
                    title: '正在上传图片...',
                    cancellable: false
                }, async (progress) => {
                    try {
                        progress.report({ increment: 0 });
                        const result = await api.uploadImage(filePath, selectedAlbumId);
                        progress.report({ increment: 100 });

                        if (result && result.status) {
                            // 复制链接到剪贴板
                            await vscode.env.clipboard.writeText(result.data.links.url);
                            vscode.window.showInformationMessage(`图片上传成功，链接已复制到剪贴板: ${result.data.links.url}`);
                             
                            // 刷新图片列表
                            treeDataProvider.refresh();
                        } else {
                            vscode.window.showErrorMessage(`图片上传失败: ${result?.message || '未知错误'}`);
                        }
                    } catch (error) {
                        vscode.window.showErrorMessage(`图片上传出错: ${error instanceof Error ? error.message : String(error)}`);
                    }
                });
            }
        } catch (error) {
            vscode.window.showErrorMessage(`执行上传命令出错: ${error instanceof Error ? error.message : String(error)}`);
        }
    });

    // 注册设置API配置命令
    const setApiConfigDisposable = vscode.commands.registerCommand('lsyk-upload-vs-plugin.setApiConfig', async () => {
        try {
            // 打开设置界面
            await vscode.commands.executeCommand('workbench.action.openSettings', 'lsyk-upload-vs-plugin');
        } catch (error) {
            vscode.window.showErrorMessage(`打开设置出错: ${error instanceof Error ? error.message : String(error)}`);
        }
    });

    // 注册复制图片URL命令
    const copyImageUrlDisposable = vscode.commands.registerCommand('lsyk-upload-vs-plugin.copyImageUrl', async (url: string) => {
        try {
            if (url) {
                // 复制链接到剪贴板
                await vscode.env.clipboard.writeText(url);
                vscode.window.showInformationMessage(`图片URL已复制到剪贴板`);
            } else {
                vscode.window.showErrorMessage('未提供图片URL');
            }
        } catch (error) {
            vscode.window.showErrorMessage(`复制图片URL出错: ${error instanceof Error ? error.message : String(error)}`);
        }
    });

    // 注册展示图片详情命令
    const showImageDetailsDisposable = vscode.commands.registerCommand('lsyk-upload-vs-plugin.showImageDetails', async (image: any) => {
        try {
            if (!image) {
                vscode.window.showErrorMessage('未提供图片数据');
                return;
            }

            // 创建Webview面板展示图片详情
            const panel = vscode.window.createWebviewPanel(
                'imageDetails',
                `图片详情: ${image.origin_name}`,
                vscode.ViewColumn.One,
                {
                    enableScripts: true,
                    retainContextWhenHidden: true
                }
            );

            // 设置Webview内容
            panel.webview.html = `
                <!DOCTYPE html>
                <html lang="zh-CN">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>图片详情</title>
                    <style>
                        body {
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
                            padding: 20px;
                            max-width: 800px;
                            margin: 0 auto;
                        }
                        .container {
                            border: 1px solid #eee;
                            border-radius: 8px;
                            padding: 20px;
                            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                        }
                        .image-container {
                            text-align: center;
                            margin-bottom: 20px;
                        }
                        .image-container img {
                            max-width: 100%;
                            max-height: 500px;
                            border-radius: 4px;
                        }
                        .info-table {
                            width: 100%;
                            border-collapse: collapse;
                            margin-top: 20px;
                        }
                        .info-table th, .info-table td {
                            padding: 10px;
                            text-align: left;
                            border-bottom: 1px solid #eee;
                        }
                        .info-table th {
                            background-color: #f5f5f5;
                            font-weight: 600;
                        }
                        .button-group {
                            margin-top: 20px;
                            display: flex;
                            gap: 10px;
                        }
                        button {
                            padding: 8px 16px;
                            background-color: #0078d7;
                            color: white;
                            border: none;
                            border-radius: 4px;
                            cursor: pointer;
                        }
                        button:hover {
                            background-color: #005a9e;
                        }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <h1>${image.origin_name}</h1>
                        <div class="image-container">
                                <img src="${image.links.thumbnail_url}" alt="${image.origin_name}">
                                <p style="margin-top: 8px; font-size: 12px; color: #666;">显示缩略图以节省流量</p>
                            </div>
                        <table class="info-table">
                            <tr>
                                <th>属性</th>
                                <th>值</th>
                            </tr>
                            <tr>
                                <td>文件大小</td>
                                <td>${(image.size / 1024).toFixed(2)} KB</td>
                            </tr>
                            <tr>
                                <td>尺寸</td>
                                <td>${image.width} × ${image.height}</td>
                            </tr>
                            <tr>
                                <td>格式</td>
                                <td>${image.mimetype || '未知'}</td>
                            </tr>
                            <tr>
                                <td>上传时间</td>
                                <td>${image.human_date || image.date}</td>
                            </tr>
                            <tr>
                                <td>MD5</td>
                                <td>${image.md5}</td>
                            </tr>
                            <tr>
                                <td>SHA1</td>
                                <td>${image.sha1}</td>
                            </tr>
                        </table>
                        <div class="button-group">
                                <button id="copyUrl">复制图片URL</button>
                                <button id="copyThumbnailUrl">复制缩略图URL</button>
                                <button id="copyMarkdown">复制Markdown链接</button>
                                <button id="copyHtml">复制HTML代码</button>
                            </div>
                    </div>
                    <script>
                        // 复制URL到剪贴板
                        document.getElementById('copyUrl').addEventListener('click', () => {
                            navigator.clipboard.writeText('${image.links.url}')
                                .then(() => vscode.postMessage({ type: 'showMessage', message: '图片URL已复制到剪贴板' }))
                                .catch(err => console.error('复制失败:', err));
                        });

                        // 复制Markdown链接
                        document.getElementById('copyMarkdown').addEventListener('click', () => {
                            navigator.clipboard.writeText('${image.links.markdown}')
                                .then(() => vscode.postMessage({ type: 'showMessage', message: 'Markdown链接已复制到剪贴板' }))
                                .catch(err => console.error('复制失败:', err));
                        });

                        // 复制HTML代码
                        document.getElementById('copyHtml').addEventListener('click', () => {
                            navigator.clipboard.writeText('${image.links.html}')
                                .then(() => vscode.postMessage({ type: 'showMessage', message: 'HTML代码已复制到剪贴板' }))
                                .catch(err => console.error('复制失败:', err));
                        });

                        // 复制缩略图URL
                        document.getElementById('copyThumbnailUrl').addEventListener('click', () => {
                            navigator.clipboard.writeText('${image.links.thumbnail_url}')
                                .then(() => vscode.postMessage({ type: 'showMessage', message: '缩略图URL已复制到剪贴板' }))
                                .catch(err => console.error('复制失败:', err));
                        });

                        // 监听来自扩展的消息
                        window.addEventListener('message', event => {
                            const message = event.data;
                            switch (message.type) {
                                case 'refresh':
                                    vscode.postMessage({ type: 'refresh' });
                                    break;
                            }
                        });
                    </script>
                </body>
                </html>
            `;

            // 监听Webview消息
            panel.webview.onDidReceiveMessage(message => {
                switch (message.type) {
                    case 'showMessage':
                        vscode.window.showInformationMessage(message.message);
                        break;
                }
            });

            // 当面板被关闭时执行清理
            panel.onDidDispose(
                () => {
                    // 执行清理工作
                },
                null,
                context.subscriptions
            );
        } catch (error) {
            vscode.window.showErrorMessage(`展示图片详情出错: ${error instanceof Error ? error.message : String(error)}`);
        }
    });

    // 注册侧边栏视图
    const treeDataProvider = new LsykUploadPanel(context, api);
    vscode.window.registerTreeDataProvider('lsyk-upload-panel', treeDataProvider);

    // 刷新视图的命令
    const refreshViewDisposable = vscode.commands.registerCommand('lsyk-upload-vs-plugin.refreshView', () => {
        treeDataProvider.refresh();
    });

    // 订阅命令
    context.subscriptions.push(
        uploadImageDisposable,
        setApiConfigDisposable,
        refreshViewDisposable,
        copyImageUrlDisposable,
        showImageDetailsDisposable
    );
}

export function deactivate() {
    console.log('lsyk-upload-vs-plugin is now deactivated!');
}